package com.wkbb.sports.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.wkbb.common.base.BaseController;
import com.wkbb.common.constants.ErrorCode;
import com.wkbb.common.constants.VersionConstant;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.common.dto.basic.GradeDto;
import com.wkbb.common.dto.basic.GradeTreeDto;
import com.wkbb.common.dto.basic.StudentInfoDto;
import com.wkbb.common.dto.basic.UserDto;
import com.wkbb.common.handler.JsonUtil;
import com.wkbb.common.utils.DateUtil;
import com.wkbb.common.utils.HttpClientUtil;
import com.wkbb.common.utils.StringUtil;
import com.wkbb.sports.dto.*;
import com.wkbb.sports.enums.SportsModelTypeEnum;
import com.wkbb.sports.enums.SportsProjectKindEnum;
import com.wkbb.sports.feign.BasicFeignService;
import com.wkbb.sports.mapper.BasicMapper;
import com.wkbb.sports.model.*;
import com.wkbb.sports.service.AppService;
import com.wkbb.sports.service.DictService;
import com.wkbb.sports.service.MetaverseService;
import com.wkbb.sports.service.StudentArenaService;
import com.wkbb.sports.utils.WxPhoneNumberAESUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.*;

@RestController
@Api(description = "元宇宙活动")
@RequestMapping("/sports/{apiVersion}/metaverse")
@Slf4j
public class MetaverseController extends BaseController {

    @Autowired
    private MetaverseService service;
    @Autowired
    private StudentArenaService studentArenaService;

    @ResponseBody
    @ApiOperation(value = "活动地点打卡")
    @RequestMapping(value = "/clockIn", method = RequestMethod.POST)
    public ResultDTO<Boolean> clockIn(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @RequestBody MetaverseClockIn data) {
        try {
            UserDto userDto = this.getRouteUserByUnion();
            if (null == userDto) {
                return new ResultDTO(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            if (data.getMetaverseUniqueId() == null){
                return ResultDTO.errorResult("用户元宇宙身份证唯一码不能为空");
            }
            if (data.getActivityLocationId() == null){
                return ResultDTO.errorResult("活动地点id不能为空");
            }
            data.setUserId(userDto.getId());
            return service.clockIn(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultDTO.errorResult("参数异常");
    }

    @ApiOperation(value = "获取已打卡地点列表")
    @GetMapping(value = "/getClockInList")
    public ResultDTO<PageInfo<MetaverseClockInDto>> getClockInList(@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
                                                                   @ApiParam(value = "分页数", defaultValue = "1") @RequestParam(name = "pageNo") int pageNo,
                                                                   @ApiParam(value = "分页大小", defaultValue = "10") @RequestParam(name = "pageSize") int pageSize) {
        try {
            UserDto userDto = this.getRouteUserByUnion();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            Map<String,Object>  map  = new HashMap<>();
            map.put("userId", userDto.getId());
            return ResultDTO.successResult(service.getClockInListByPage(map,pageNo,pageSize));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResultDTO<>(false);
    }

    @ResponseBody
    @ApiOperation(value = "领取元宇宙身份证")
    @RequestMapping(value = "/putMetaverseID", method = RequestMethod.POST)
    public ResultDTO<MetaverseID> putMetaverseID(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @RequestBody MetaverseID data) {
        try {
            UserDto userDto = this.getRouteUserByUnion();
            if (null == userDto) {
                return new ResultDTO(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            data.setUserId(userDto.getId());
            return service.putMetaverseID(data);
        } catch (Exception e) {
            return new ResultDTO();
        }
    }

    @ApiOperation(value = "获取当前元宇宙身份证信息")
    @GetMapping(value = "/getMetaverseID")
    public ResultDTO<MetaverseID> getMetaverseID(@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion) {
        try {
            UserDto userDto = this.getRouteUserByUnion();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            return ResultDTO.successResult(service.getMetaverseIDByUserId(userDto.getId()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResultDTO<>(false);
    }

    @ApiOperation(value = "获取元宇宙活动地点列表")
    @GetMapping(value = "/getMetaverseActivityLocationList")
    public ResultDTO<List<MetaverseActivityLocation>> getMetaverseActivityLocationList(@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion) {
        try {
            UserDto userDto = this.getRouteUserByUnion();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            return ResultDTO.successResult(service.getMetaverseActivityLocationList());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResultDTO<>(false);
    }

    @ApiOperation(value = "元宇宙活动地点批量导入", notes = "")
    @PostMapping(value = "putMetaverseActivityLocationList")
    public ResultDTO<String> putMetaverseActivityLocationList(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @RequestParam("uploadFile") MultipartFile uploadFile) {
        if (null == uploadFile) {
            return new ResultDTO(ErrorCode.PARAM_MISSING);
        }
        InputStream in = null;
        try {
            in = uploadFile.getInputStream();
            List<Object> excelData = EasyExcel.read(in).sheet().doReadSync();
            List<MetaverseActivityLocation> list = new ArrayList<>();
            List<StudentArena> arenaList = new ArrayList<>();
            Date startTime = DateUtil.dateMinSDF.parse("2023-3-22 20:00");
            Date endTime = DateUtil.dateMinSDF.parse("2023-4-20 20:00");
            for (Object object : excelData) {
                Map<Integer, String> map = (Map<Integer, String>) object;
//                log.info("map:"+JsonUtil.objectToJson(map));
                MetaverseActivityLocation item = new MetaverseActivityLocation();
                String name = map.get(1);
                if (name == null){
                    break;
                }
                item.setName(name);
                item.setConstructionSituation(map.get(2));
                item.setFusionConstructionSituation(map.get(3));
                item.setRemark(map.get(4));
                item.setAddress(map.get(5));
                String location = map.get(6);
                if (location != null) {
                    String[] arr = location.split(",");
                    if (arr.length == 2){
                        item.setLongitude(Double.parseDouble(arr[0]));
                        item.setLatitude(Double.parseDouble(arr[1]));
                    }
                }

                String arenaName = map.get(7);
                arenaName = StringUtil.isEmpty(arenaName)? "天河区新时代文明实践中心":arenaName.trim();
                item.setArenaName(arenaName);

                String star = map.get(8);
                int starLevel = StringUtil.isEmpty(star)?5:Integer.parseInt(star.trim());
                item.setStarLevel(starLevel);

                String intro = map.get(9);
                intro = StringUtil.isEmpty(intro)? item.getAddress():intro.trim();
                item.setIntro(intro);

//                String type = map.get(10);
//                type = StringUtil.isEmpty(type)? "商圈" : type.trim();
//                item.setType(type);
//                list.add(item);

                item.setType(item.getRemark());
                list.add(item);

                //擂台
                StudentArena studentArena = new StudentArena();
                studentArena.setName(item.getArenaName());
                studentArena.setOfficial(true);
                studentArena.setGradeIds("");
                studentArena.setGradeNames("不限");
                studentArena.setOriginatorName("官方");
                studentArena.setWay(2);
                studentArena.setLongitude(item.getLongitude());
                studentArena.setLatitude(item.getLatitude());
                studentArena.setAddress(item.getAddress());
                studentArena.setFaceRecognition(false);
                studentArena.setModelType(1);
                studentArena.setJumpType(1);
                studentArena.setGenerateInviteCode(false);
                studentArena.setIntroduce(null);
                studentArena.setJumpType(1);
                studentArena.setStudentId(1L);
                studentArena.setType(1);
                studentArena.setTrainRequire(60);
                studentArena.setChallengeNum(0);
                studentArena.setChallengeCount(0);
                studentArena.setChallengeTeamNum(0);
                studentArena.setStartTime(startTime);
                studentArena.setEndTime(endTime);
                studentArena.setIntroduce(item.getIntro());
                studentArena.setShowArea(1);
                arenaList.add(studentArena);
            }
//            log.info("putMetaverseActivityLocationList:" + JsonUtil.objectToJson(list));
            int count = list.isEmpty()?0:service.putMetaverseActivityLocationList(list);
            studentArenaService.insertBatch(arenaList);
            //被强制取消，处理完所有线程后，再返回给用户界面提示异常
            return new ResultDTO<>("成功导入" + count + "条");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return new ResultDTO<>(false);
    }



}